//
//  Tools.m
//  CNPText
//
//  Created by cnp on 17/3/31.
//  Copyright © 2017年 CNP. All rights reserved.
//

#import "Tools.h"



#import <AVFoundation/AVFoundation.h>

#import <AFNetworking.h>

static makesurebutton confirmParam;

static canclebutton  cancleParam;

@interface Tools()

@end

@implementation Tools
#pragma mark----设置系统的导航、分栏属性
/**
 * 设置系统的导航、分栏属性
 *
 *
 */
+(void)setAppearance
{
    //导航
    UIImage *image=[Tools imageWithColor:[UIColor whiteColor] size:CGSizeMake(HDScreenWidth, NaviHight)];
    [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    
    NSDictionary * navTitleTextAttributesDic = @{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]};
    [[UINavigationBar appearance]setTitleTextAttributes:navTitleTextAttributesDic];//控制title颜色字体;
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];//控制 barButtonItem返回图片的颜色字体颜色;
    

    
    //分栏
    UIColor *color2=[Tools hexStringToColor:@"999999"];
    NSDictionary *barButtonItemDic=@{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    [[UIBarButtonItem appearance]setTitleTextAttributes:barButtonItemDic forState:UIControlStateNormal];//控制返回字体的大小;
    NSDictionary *tabBarItemAttributesDicNormal=@{NSForegroundColorAttributeName:color2,NSFontAttributeName:[UIFont boldSystemFontOfSize:10]};
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                         forBarMetrics:UIBarMetricsDefault];
    
    //选中字体颜色
    NSDictionary *tabBarItemAttributesDicSelect=@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:10]};
    [[UITabBarItem appearance]setTitleTextAttributes:tabBarItemAttributesDicNormal forState:UIControlStateNormal];
    [[UITabBarItem appearance]setTitleTextAttributes:tabBarItemAttributesDicSelect forState:UIControlStateSelected];//tabbaritem 字体的大小颜色;
}
#pragma mark----判断手机号、邮箱
/**
 * 判断手机号
 *
 *  @param mobileNum 手机号
 *
 *  @return  正确手机号
 */
+(BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 移动号段正则表达式
     */
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     * 联通号段正则表达式
     */
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     * 电信号段正则表达式
     */
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobileNum];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobileNum];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobileNum];
    if (isMatch1 || isMatch2 || isMatch3) {
        return nil;
        
    }else{
        return @"请输入正确的*****号码";
    }
}
/**
 * 判断邮箱
 *
 *  @param email 邮箱号
 *
 *  @return  正确邮箱
 */
+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
#pragma mark----颜色表示
/**
 * 16进制颜色(html颜色值)字符串转为UIColor
 *
 *  @param  stringToConvert 16进制字符串
 *
 *  @return UIColor;
 */
+(UIColor *) hexStringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}
#pragma mark----不同大小和颜色的字符串组合
/**
 * 不同大小和颜色的字符串组合
 *
 *  @param string1 字符串1
 *  @param color1 字符串1的颜色
 *  @param font1 字符串1的大小
 *  @param string2 字符串2
 *  @param color2 字符串2的颜色
 *  @param font2 字符串2的大小
 *
 *  @return  NSMutableAttributedString
 */
+(NSMutableAttributedString *)DifferentString1:(NSString *)string1 color1:(UIColor *)color1 font1:(NSInteger)font1  string2:(NSString *)string2 color2:(UIColor *)color2 font2:(NSInteger)font2
{
    NSString *str=[NSString stringWithFormat:@"%@%@",string1,string2];
    
    NSMutableAttributedString *string=[[NSMutableAttributedString alloc]initWithString:str];
    [string addAttribute:NSForegroundColorAttributeName value:color1 range:NSMakeRange(0, string1.length)];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font1] range:NSMakeRange(0, string1.length)];
    
    [string addAttribute:NSForegroundColorAttributeName value:color2 range:NSMakeRange(string1.length, string2.length)];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font2] range:NSMakeRange(string1.length, string2.length)];
    return string;
}
/**
 * 不同大小和颜色的字符串组合
 *
 *  @param string1 字符串1
 *  @param color1 字符串1的颜色
 *  @param font1 字符串1的大小
 *  @param string2 字符串2
 *  @param color2 字符串2的颜色
 *  @param font2 字符串2的大小
 *  @param string3 字符串3
 *  @param color3 字符串3的颜色
 *  @param font3 字符串3的大小
 *
 *  @return  NSMutableAttributedString
 */
+(NSMutableAttributedString *)DifferentString1:(NSString *)string1 color1:(UIColor *)color1 font1:(NSInteger)font1  string2:(NSString *)string2 color2:(UIColor *)color2 font2:(NSInteger)font2 string3:(NSString *)string3 color3:(UIColor *)color3 font3:(NSInteger)font3
{
    NSString *str=[NSString stringWithFormat:@"%@%@%@",string1,string2,string3];
    
    NSMutableAttributedString *string=[[NSMutableAttributedString alloc]initWithString:str];
    //
    [string addAttribute:NSForegroundColorAttributeName value:color1 range:NSMakeRange(0, string1.length)];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font1] range:NSMakeRange(0, string1.length)];
    
    //
    [string addAttribute:NSForegroundColorAttributeName value:color2 range:NSMakeRange(string1.length, string2.length)];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font2] range:NSMakeRange(string1.length, string2.length)];
    //
    [string addAttribute:NSForegroundColorAttributeName value:color3 range:NSMakeRange(string2.length+string1.length, string3.length)];
    [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font3] range:NSMakeRange(string2.length+string1.length, string3.length)];
    return string;
}
#pragma mark----初始化UIImage
/**
 * 初始化UIImage
 *
 *  @param color 颜色
 *  @param size  大小
 *
 *  @return  UIImage
 */
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark----计算字符串的宽度和高度
/**
 *  计算字符串的宽度
 *
 *  @param string 字符串
 *  @param stringHeight  允许的高度
 *  @param fontSize  大小
 *
 *  @return  width
 */
+(CGFloat)widthForWithNSSting:(NSString *)string stringHeight:(CGFloat )stringHeight fontSize:(CGFloat)fontSize
{
    CGRect rect=  [string boundingRectWithSize:CGSizeMake(HDScreenWidth*2, stringHeight) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin  attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
    return rect.size.width;
}
/**
 *  计算字符串的高度
 *
 *  @param string 字符串
 *  @param stringWidth  允许的宽度
 *  @param fontSize  大小
 *
 *  @return  height
 */
+(CGFloat)heightForWithNSSting:(NSString *)string stringWidth:(CGFloat )stringWidth fontSize:(CGFloat)fontSize;
{
    CGRect rect=  [string boundingRectWithSize:CGSizeMake(stringWidth, HDScreenHeight) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin  attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
    return rect.size.height;
}
#pragma mark----清空字符串中的空白字符
/**
 * 清空字符串中的空白字符
 *
 *  @param string 字符串
 *
 *  @return  NSMutableAttributedString
 */
+ (NSString *)trimString:(NSString *)string
{
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#pragma mark----时间
/**
 * 得到当前时间戳
 *
 *
 *  @return  时间戳
 */
+(NSString *)getNowTimeString
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%f",a];
    
    return timeString;
}
/**
 * 时间戳转时间字符串
 *
 *  @param timebunber 时间戳
 *
 *  @return  时间字符串
 */
+(NSString *)timenumberchangetime:(int)timebunber
{
    NSString *string;
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timebunber];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    string=[NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:confromTimesp]];
    return string;
}
#pragma mark----UIAlertView提示框
/**
 *  消息提示框
 *
 *  @param ViewController 当前控制器
 *  @param message  提示语
 *
 */
+(void)ShowAlertView:(UIViewController *)ViewController message:(NSString *)message
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        }];
        [alertController addAction:cancelAction];
        [ViewController presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertview show];
    }
}
/**
 *  提示框
 *
 *  @param ViewController 当前控制器
 *  @param message  提示语
 *  @param makesurebutton   确定按钮事件
 *
 */
+(void)ShowAlertView:(UIViewController *)ViewController message:(NSString *)message makesurebutton:(makesurebutton)makesurebutton
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            makesurebutton();
        }];
        [alertController addAction:cancelAction];
        [ViewController presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        confirmParam=makesurebutton;
        UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alertview.delegate=self;
        [alertview show];
    }
}
/**
 *  提示框
 *
 *  @param viewController 当前控制器
 *  @param message  提示语
 *  @param cancelButtonTitle  取消
 *  @param otherButtonTitle  确定
 *  @param canclebutton  取消事件
 *  @param makesurebutton  确定事件
 *
 */
+(void)showAlertView:(UIViewController *)viewController title:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitle:(NSString *)otherButtonTitle  canclebutton:(canclebutton)canclebutton makesurebutton:(makesurebutton)makesurebutton
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        // Create the actions.
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            canclebutton();
        }];
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            makesurebutton();
        }];
        // Add the actions.
        [alertController addAction:cancelAction];
        [alertController addAction:otherAction];
        [viewController presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        confirmParam=canclebutton;
        cancleParam=makesurebutton;
        UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitle,nil];
        [alertview show];
    }
}
/**
 *  提示框代理方法
 *
 *  @param alertView 提示框
 *  @param buttonIndex  选择的按钮ID
 *
 */
+(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        confirmParam();
    }
    else
    {
        cancleParam();
    }
}
#pragma mark----在本地存取删数据
/**
 *  存储数据到本地
 *
 *  @param content 内容
 *  @param key  键值
 *
 */
+(void)SaveDatatoLocalofContent:(id)content key:(NSString *)key
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setObject:content forKey:key];
    [user synchronize];
}
/**
 *  从本地取数据
 *
 *  @param key  键值
 *
 */
+(id)AskDatafromLocalofNSString:(NSString *)key
{
    id content;
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    content=[user objectForKey:key];
    return content;
}
/**
 *  从本地删除数据
 *
 *  @param key  键值
 *
 **/
+(void)delegateDatafromBase:(NSString *)key
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user removeObjectForKey:key];
    [user synchronize];
}
#pragma mark----不可变字典变成可变字典
/**
 * 不可变字典变成可变字典
 *
 *  @param Dictionary  不可变字典
 *
 *  @return  NSMutableDictionary
 **/
+(NSMutableDictionary *)DictionarychangtoNsmutabledictionary:(NSDictionary *)Dictionary
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *arrrary1=[Dictionary allKeys];
    NSArray *arrary2=[Dictionary allValues];
    for (int m=0; m<arrrary1.count; m++) {
        [dic setObject:arrary2[m] forKey:arrrary1[m]];
    }
    return dic;
}
#pragma mark----拼接数组内容成字符串
/**
 * 拼接数组内容成字符串
 *
 *  @param arrary  数组
 *
 *  @return  NSString
 **/
+(NSString *)addArraryContentToString:(NSArray *)arrary
{
    
    NSString *str=@"| ";
    for (int m=0; m<arrary.count; m++)
    {
        str=[NSString stringWithFormat:@"%@%@%@  ",str,@"# ",arrary[m]];
    }
    return str;
}
#pragma mark----删除子视图
/**
 * 删除子视图
 *
 *  @param fatherview  父视图
 *  @param childviewtag  子视图
 *
 **/
+(void)delegateviewfromFatherview:(UIView *)fatherview childviewtag:(int)childviewtag
{
    for (UIView *childview in [fatherview subviews]) {
        if (childview.tag==childviewtag) {
            [childview removeFromSuperview];
        }
    }
}
#pragma mark----切换动画
/**
 * 删除子视图
 *
 *  @param subview  父视图
 *  @param type     样式
 *  @param subtype  方向
 *
 **/
+(void)ExchangeViewofCATransitionWithType:(NSString *)type subtype:(NSString *)subtype subview:(UIView *)subview
{
    CATransition *transiton = [CATransition animation];
    
    transiton.type = type;
    
    transiton.subtype =subtype;
    
    
    [subview.layer addAnimation:transiton forKey:@"tran"];
}
#pragma mark----一维数组变成二维数组
/**
 * 一维数组变成二维数组
 *
 *  @param oneArrary  一维数组
 *  @param number     数组元素个数
 *
 **/
+(NSArray *)OneArraryChangeTwoArrary:(NSArray *)oneArrary number:(int)number
{
    
    NSMutableArray *data1=[NSMutableArray array];
    NSMutableArray *data2=[NSMutableArray array];
    
    for (int m=0; m<oneArrary.count; m++) {
        
        if (m%number==0) {
            
            data1=[NSMutableArray array];
            [data2 addObject:data1];
        }
        [data1 addObject:oneArrary[m]];
    }
    return  data2;
    
}
#pragma mark---- 压缩图片
/**
 *   压缩图片
 *
 *  @return UIImage
 */
+(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
#pragma mark----设置导航栏属性
/**
 *
 *   设置导航title字体颜色和大小
 *
 **/
+(void)setNvrTitleWithviewcontroller:(UIViewController *)viewcontroller Color:(UIColor *)color font:(NSInteger)font
{
    [viewcontroller.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font], NSForegroundColorAttributeName:color}];
}
/**
 *
 *   设置导航背景颜色
 *
 **/
+(void)setNvrBackgroundColorWithViewcontroller:(UIViewController *)viewcontroller Color:(UIColor *)color
{
    [viewcontroller.navigationController.navigationBar setBackgroundImage:[Tools imageWithColor:color size:CGSizeMake(HDScreenWidth, NaviHight)] forBarMetrics:UIBarMetricsDefault];
}
/**
 *
 *   获取网络图片的尺寸
 *
 **/
+(CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
//  获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取gif图片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取jpg图片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}
#pragma mark----获取URL视频的图片
/**
 *
 *   获取网络图片
 *
 **/
+ (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
    
    return thumbnailImage;
}
#pragma mark----无数据view
/**
 *
 *   无数据view
 *
 **/
//+(void)addNoDataView:(UIView *)footView;
//{
//    BaseNoDataView *nodataview=[[BaseNoDataView alloc]initWithFrame:footView.frame];
//    nodataview.tag=10001000;
//    nodataview.backgroundColor=[UIColor clearColor];
//    [footView addSubview:nodataview];
//}
+(void)deleteNodataView:(UIView *)footview
{
    [Tools delegateviewfromFatherview:footview childviewtag:10001000];
}
/**
 判断网络类型
 */
+(void)judgenetworking
{
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    // 开始监控
    [manger startMonitoring];
     //2.监听改变
    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                [Tools SaveDatatoLocalofContent:@"0" key:@"IsDataFlow"];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                [Tools SaveDatatoLocalofContent:@"0" key:@"IsDataFlow"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G|4G");
                [Tools SaveDatatoLocalofContent:@"1" key:@"IsDataFlow"];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi");
                [Tools SaveDatatoLocalofContent:@"0" key:@"IsDataFlow"];
                break;
            default:
                break;
        }

    }];

}

/**
 开启一个定时器
 
 @param target 定时器持有者
 @param timeInterval 执行间隔时间
 @param handler 重复执行事件
 */
void dispatchTimer(id target, double timeInterval,void (^handler)(dispatch_source_t timer))
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
    // 设置回调
    __weak __typeof(target) weaktarget  = target;
    dispatch_source_set_event_handler(timer, ^{
        if (!weaktarget)  {
            dispatch_source_cancel(timer);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (handler) handler(timer);
            });
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}

/**
 *  将当前的countdownTimeStr信息转换成时间字符串： 00：00
 */
+(NSString *)currentTimeStringWith:(int)countdownTime{
//    UIGraphicsBeginImageContext(newSize);
//    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//
//    return newImage;
    
    NSString *str;
    if (countdownTime <= 0) {
        
       str= @"00:00:00";
        
    } else {
        
        str = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)countdownTime/3600,(long)countdownTime%3600/60,(long)countdownTime%60];
    }
    
    return str;
    
    
}







@end
